<template>
  <div class="star-content-container">
    <div class="star-content-left">
      <unit-select @getSelectUnit="getSelectUnit"></unit-select>
      <el-input class="tree-input" v-model="filterText" placeholder="请输入过滤条件" :suffix-icon="Search" />
      <el-tree
        ref="treeRef"
        v-if="treeVisible"
        :load="loadNode"
        lazy
        node-key="value"
        :props="defaultProps"
        :highlight-current="true"
        :default-expanded-keys="[0]"
        :expand-on-click-node="false"
        @node-click="handleClickNode"
        :filter-node-method="filterNode"
      >
      <template #default="{ data }">
        <span>
          <span>
            <el-icon v-if="data.isLeaf===true"><User /></el-icon>
            <el-icon v-else><House /></el-icon>
            {{ data.label }}
          </span>
        </span>
      </template>
      </el-tree>
    </div>
    <div class="star-content-right">
      <user-list :fid="deptFid" :id="userId" @change-data="reLoadTree"/>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElTree } from 'element-plus'
import { onMounted, ref, watch, inject, nextTick } from 'vue'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { Search } from '@element-plus/icons-vue'
// import UserEditTab from './UserEditTab.vue'
import userList from '@/views/system/user/UserList.vue'
import { loadAllDept } from '@/api/system/dept/DeptManager'
import UnitSelect from '@/components/common/select/UnitSelect.vue'
import { loadAllUserTree } from '@/api/system/user/UserManager'

import '@/style/layout.less'

const treeRef = ref()
const deptFid = ref('0')
const deptTree = ref([])
const filterText = ref('')
const treeVisible = ref(true)
const unitId = ref()
const userId = ref('')
const iconData = ref()

const filterNode = (value, data) => {
  if (!value) return true
  return data.label.includes(value)
}

const defaultProps = {
  children: 'children',
  label: 'label',
  // disabled: 'disabled',
  isLeaf: 'leaf',
  icon: 'icon'
}

interface Tree {
  label: string
  leaf?: boolean
}

watch(filterText, (val) => {
  treeRef.value.filter(val)
})

const handleClickNode = (node) => {
  deptFid.value = node.value
  if (node.isLeaf) {
    userId.value = node.value
    return
  }
  userId.value = ''
}

const loadNode = (node: Node, resolve: (data: Tree[]) => void) => {
  let fid = node.data.value
  if (fid === undefined || fid === '') {
    fid = unitId.value
  }
  setTimeout(() => {
    loadAllUserTree({ fid: fid, search: '' }).then((data) => {
      resolve(data.data)
    })
  }, 500)
}

const getSelectUnit = (emitUnitId:string) => {
  unitId.value = emitUnitId
  treeVisible.value = false
  nextTick(() => {
    treeVisible.value = true
  })
  deptFid.value = ''
}

const reLoadTree = () => {
  treeVisible.value = false
  nextTick(() => {
    treeVisible.value = true
  })
  deptFid.value = ''
}

</script>

<style lang="less" scoped>
@import '../../../style/tree.less';
</style>
